<!-- 滚动效果设置 -->
<template>
  <div>
    <el-drawer
      v-model="visible"
      :title="props.title"
      :size="props.width"
      :before-close="hide"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :modal="true"
    >
      <template #title>
        <div class="flex flex-col">
          <div class="drawer-header">
            <div class="flex items-center dot" v-if="showDot">
              <div class="w-[5px] h-[5px] rounded-1/2 bg-[#3721FF]"></div>
              <span class="ml-2 drawer-title">{{ props.title }}</span>
            </div>
          </div>
          <div class="text-[12px] mt-[4px] text-[#999] desc">{{ props.titleDesc }}</div>
        </div>
      </template>
      <div class="drawer-content">
        <slot></slot>
        <div>
          <div>
            <el-form
              label-width="100px"
              :model="rollingForm"
              ref="dataFormRef"
              :rules="rollingRules"
              class="w-[80%]"
              label-position="left"
            >
              <el-form-item label="分类名称" prop="categoryName">
                <el-input v-model="rollingForm.categoryName" placeholder="请输入分类名称" />
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="地区" prop="areaId" required>
                    <el-select
                      v-model="rollingForm.areaId"
                      placeholder="请选择地区"
                      @change="handleArea"
                    >
                      <el-option
                        v-for="item in salesRegion"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="语言" prop="language" required label-width="60px">
                    <el-select v-model="rollingForm.language" placeholder="请选择地区">
                      <el-option
                        v-for="item in languageList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item prop="style" label="滚动样式" required>
                <div class="scroll-style-box">
                  <el-radio-group
                    v-model="rollingForm.style"
                    :disabled="rollingForm.id ? true : false"
                    @change="handleStyle"
                  >
                    <el-radio value="1">
                      <div class="scroll-style">
                        <img
                          class="w-[31px] h-[31px]"
                          src="https://img.alicdn.com/imgextra/i2/1034622205/O1CN01xMfDFC1S9wOrWiSRn_!!1034622205.png"
                          alt=""
                        />
                        <span class="ml-2 line-height-[14px] text-[14px] mt-2">样式1</span>
                        <span class="ml-2 text-[12px] text-[#999]">描述描述描述描述</span>
                      </div>
                    </el-radio>
                    <el-radio value="2">
                      <div class="scroll-style">
                        <img
                          class="w-[31px] h-[31px]"
                          src="https://img.alicdn.com/imgextra/i2/1034622205/O1CN01xMfDFC1S9wOrWiSRn_!!1034622205.png"
                          alt=""
                        />
                        <span class="ml-2 line-height-[14px] text-[14px] mt-2">样式2</span>
                        <span class="ml-2 text-[12px] text-[#999]">描述描述描述描述</span>
                      </div>
                    </el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
              <el-form-item
                label-width="140px"
                label="评论时间显示规则"
                prop="timeRule"
                v-if="rollingForm.style == '2'"
              >
                <el-select v-model="rollingForm.timeRule" placeholder="请选择评论时间显示规则">
                  <el-option label="规则1" value="1" />
                  <el-option label="规则2" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="使用权限" prop="usePermission" class="users">
                <el-radio-group v-model="rollingForm.usePermission">
                  <el-radio :label="1">仅自己</el-radio>
                  <el-radio :label="2">所有人</el-radio>
                  <el-radio :label="3">指定人员</el-radio>
                </el-radio-group>
                <div class="block">
                  <div v-if="rollingForm.usePermission == 3" class="flex">
                    <el-button type="primary" color="#3721FF" @click="handleSelectUser">
                      选择人
                    </el-button>
                    <div class="ml-2">
                      <!-- 最大只显示三个名字，多的后+几个人 -->
                      <template v-for="(item, index) in rollingForm.userList" :key="index">
                        <el-button type="primary" plain color="#3721FF" v-if="index < 3">
                          <span>{{ item.nickName }}</span>
                          <Icon
                            icon="material-symbols-light:cancel"
                            class="ml-2 text-[#999]"
                            @click.stop="handleRemoveUser(index)"
                          />
                        </el-button>
                      </template>
                      <span class="ml-2 text-[#3721FF" v-if="rollingForm?.userList?.length > 3">
                        ... {{ rollingForm?.userList?.length - 3 }}人</span
                      >
                    </div>
                  </div>
                </div>
                <!-- <el-select
                  v-model="rollingForm.userList"
                  placeholder="请选择指定人员"
                  multiple
                  v-if="rollingForm.usePermission == 3"
                >
                  <el-option label="指定人员1" value="1" />
                  <el-option label="指定人员2" value="2" />
                </el-select> -->
              </el-form-item>
              <el-form-item label="滚动数据" prop="rollData">
                <div class="el-btn">
                  <el-button type="primary" color="#3721FF" @click="handleAddRollingData">
                    + 新增
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div>
            <el-table
              :data="rollingForm.commentList"
              style="width: 100%"
              :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
            >
              <el-table-column
                prop="headPortrait"
                label="用户头像"
                width="100"
                v-if="rollingForm.style == '1'"
              >
                <template #default="scope">
                  <img
                    v-if="scope.row.headPortrait"
                    class="w-[30px] h-[30px] rounded-[50%]"
                    :src="scope.row.headPortrait"
                    alt=""
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="userName"
                label="用户名称"
                width="180"
                v-if="rollingForm.style == '2'"
              />
              <el-table-column
                prop="areaName"
                label="地区"
                width="180"
                v-if="rollingForm.style == '2'"
              />
              <el-table-column prop="content" label="滚动评论" />
              <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter" />
              <el-table-column label="操作" width="120">
                <template #default="{ $index }">
                  <!-- <el-button type="primary" plain link color="#3721FF">编辑</el-button> -->
                  <el-button type="danger" plain link @click="handleCommentDelete($index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="el-dia-btn">
          <el-button @click="hide">取消</el-button>
          <el-button type="primary" color="#3721FF" :loading="loading" @click="submit">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 新增 -->
    <ComfirmPops
      ref="addRollingDataPopsRef"
      :show-icon="false"
      width="500px"
      :show-dot="true"
      type="idTips"
      :id="selectedId"
      title="新增滚动数据"
      @confirm="getAddPops"
    >
      <template #content>
        <div>
          <el-form
            ref="addFormRef"
            :model="addRollingForm"
            :rules="addRollingFormRules"
            label-width="80px"
          >
            <template v-if="rollingForm.style == '1'">
              <el-form-item label="用户头像" prop="headPortrait">
                <UploadImg v-model="addRollingForm.headPortrait" :limit="1" :is-show-tip="false" />
              </el-form-item>
              <el-form-item label="滚动文字" prop="picUrl">
                <el-input
                  type="textarea"
                  v-model="addRollingForm.content"
                  :autosize="{ minRows: 4, maxRows: 6 }"
                />
              </el-form-item>
            </template>
            <template v-if="rollingForm.style == '2'">
              <el-form-item label="用户名称" prop="userName">
                <el-input v-model="addRollingForm.userName" placeholder="请输入用户名称" />
              </el-form-item>
              <el-form-item label="地区" prop="areaId">
                <el-select
                  v-model="addRollingForm.areaId"
                  placeholder="请选择地区"
                  @change="handleAreaChange"
                >
                  <el-option
                    v-for="item in salesRegion"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="评论时间" prop="createTime" v-if="rollingForm.timeRule == '1'">
                <el-date-picker
                  v-model="addRollingForm.createTime"
                  type="date"
                  placeholder="请选择评论时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="滚动评论" prop="content">
                <el-input
                  type="textarea"
                  v-model="addRollingForm.content"
                  :autosize="{ minRows: 4, maxRows: 6 }"
                />
              </el-form-item>
            </template>
          </el-form>
        </div>
      </template>
    </ComfirmPops>
  </div>
  <SelectUsers
    ref="selectUserRef"
    @select-user="updateSelectUser"
    :userList="rollingForm.userList"
  />
</template>

<script setup lang="ts">
defineOptions({ name: 'RollingEffect' })
import { dateFormatter } from '@/utils/formatTime'

import { createRoll, updateRoll } from '@/api/roll/index'
import SelectUsers from '@/components/SelectUser/index.vue'
import { getGlobeState, getGlobeStateByIdList } from '@/api/publicInterf/index.ts'
import { getRoll, createRollComment, deleteRollComment } from '@/api/roll/index'
const addFormRef = ref()
const loading = ref(false)
const dataFormRef = ref()
const salesRegion = ref([]) // 地区
const visible = ref(false)
const addRollingDataPopsRef = ref()
const selectedRegions = ref([])
const selectUserRef = ref()
const props = defineProps({
  showDot: {
    type: Boolean,
    default: false
  },
  isBatchImport: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '批量导入'
  },
  titleDesc: {
    type: String,
    default: ''
  },
  // 宽度
  width: {
    type: String,
    default: '50%'
  }
})
const emit = defineEmits(['close', 'confirm'])
const rollingForm = reactive({
  id: '',
  categoryName: '',
  language: '',
  areaId: '',
  areaName: '',
  style: '1',
  timeRule: '',
  usePermission: 1,
  userList: [
    {
      userId: '',
      nickName: ''
    }
  ],
  commentList: [] //滚动数据
})
let addRollingForm = reactive({
  userName: '',
  headPortrait: '',
  areaId: null,
  areaName: '',
  createTime: '',
  content: ''
})
const addRollingFormRules = reactive({
  userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
  areaId: [{ required: true, message: '请选择地区', trigger: 'blur' }],
  content: [{ required: true, message: '请输入滚动评论', trigger: 'blur' }]
})
const rollingRules = reactive({
  categoryName: [{ required: true, message: '请选择滚动效果', trigger: 'change' }],
  language: [{ required: true, message: '请选择语言', trigger: 'change' }],
  areaId: [{ required: true, message: '请选择地区', trigger: 'change' }],
  style: [{ required: true, message: '请选择样式', trigger: 'change' }],
  timeRule: [{ required: true, message: '请选择时间规则', trigger: 'change' }],
  usePermission: [{ required: true, message: '请选择使用权限', trigger: 'change' }]
})
const updateSelectUser = (data) => {
  rollingForm.userList = data.map((item) => ({
    userId: item.id,
    nickName: item.name
  }))
  console.log('data', rollingForm.userList)
}
//
const handleSelectUser = () => {
  selectUserRef.value?.open()
}

// shanchu
const handleCommentDelete = (index) => {
  if (selsectType.value == 'update') {
    deleteRollComment(rollingForm.commentList[index].id).then(() => {
      ElMessage.success('删除成功')
      handlegetRoll()
    })
  } else {
    rollingForm.commentList.splice(index, 1)
  }
}
//
const handleRemoveUser = (index) => {
  rollingForm.userList.splice(index, 1)
}
// 获取areaname
const handleAreaChange = () => {
  const area = salesRegion.value.find((item) => item.value === addRollingForm.areaId)
  addRollingForm.areaName = area?.label
}
// 获取语言
const handleArea = () => {
  rollingForm.language = ''
  handleGetGlobeStateByIdList()
  const area = salesRegion.value.find((item) => item.value === rollingForm.areaId)
  rollingForm.areaName = area?.label
}
const handleStyle = () => {
  rollingForm.commentList = []
}
// 语言
const languageList = ref([]) //语言
const handleGetGlobeStateByIdList = async () => {
  try {
    const res = await getGlobeStateByIdList({ id: rollingForm.areaId })
    console.log(res)
    languageList.value = res.map((item) => ({
      label: item,
      value: item
    }))
  } catch (error) {
    console.error('获取全局状态失败:', error)
  }
}
// 地区
const handleGetGlobeState = async () => {
  try {
    const res = await getGlobeState()
    console.log(res)
    salesRegion.value = res.map((item) => ({
      label: item.stateName,
      value: item.id
    }))
  } catch (error) {
    console.error('获取全局状态失败:', error)
  }
}

const handleAddRollingData = () => {
  if (!rollingForm.timeRule && rollingForm.style == '2') {
    return ElMessage.error('请选择评论时间显示规则')
  }
  addRollingDataPopsRef.value?.show(rollingForm.id)
  resetForm2()
}
const getAddPops = (bool, id) => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      addRollingForm.areaName = salesRegion.value.find(
        (item) => item.value == addRollingForm.areaId
      )?.label
      if (selsectType.value != '' && selsectType.value == 'update') {
        createRollComment({ timeRule: rollingForm.timeRule, rollId: id, ...addRollingForm }).then(
          () => {
            ElMessage.success('操作成功')
            addRollingDataPopsRef.value?.hide()
            resetForm2()
            getRoll({ id: selectedId.value }).then((res) => {
              rollingForm.commentList = res.commentList
            })
          }
        )
      } else {
        rollingForm.commentList.push(JSON.parse(JSON.stringify(addRollingForm)))
        addRollingDataPopsRef.value?.hide()
        resetForm2()
      }
      addRollingDataPopsRef.value?.hide()
    }
  })
}
const submit = () => {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      let params = JSON.parse(JSON.stringify(rollingForm))
      params.areaName = salesRegion.value.find((item) => item.value == rollingForm.areaId)?.label
      loading.value = true
      if (selectedId.value) {
        delete params.commentList
        updateRoll(params).then(() => {
          ElMessage.success('操作成功')
          emit('confirm')
          hide()
          loading.value = false
        }).catch(() => {
          loading.value = false
        })
      } else {
        params.commentList.map((item) => {
          item.areaId = item.areaId == '' ? null : item.areaId
        })
        createRoll(params).then(() => {
          ElMessage.success('操作成功')
          emit('confirm')
          hide()
          loading.value = false
        }).catch(() => {
          loading.value = false
        })
      }
    }
  })
}
const selectedId = ref() //选中id
const selsectType = ref() //选中类型
const show = (type, id) => {
  console.log(type, id)
  selsectType.value = type
  visible.value = true
  if (type == 'update') {
    selectedId.value = id
    handlegetRoll()
  } else {
    // 如果是新增，编辑的值都清空
    resetForm1()
    selectedId.value = ''
  }
}
// 选中查询
const handlegetRoll = async () => {
  await getRoll({ id: selectedId.value }).then((res) => {
    rollingForm.id = res.id
    rollingForm.categoryName = res.categoryName
    rollingForm.language = res.language
    rollingForm.areaId = res.areaId
    rollingForm.style = res.style
    rollingForm.timeRule = res.timeRule
    rollingForm.usePermission = res.usePermission
    rollingForm.userList = res.userList
    rollingForm.commentList = res.commentList
  })
}
const hide = () => {
  visible.value = false
  emit('close')
}
// 新增重置表单方法
const resetForm1 = () => {
  // 重置主表单
  Object.assign(rollingForm, {
    id: '',
    categoryName: '',
    language: '',
    areaId: '',
    areaName: '',
    style: '1',
    timeRule: '',
    usePermission: 1,
    userList: [],
    commentList: []
  })
}
const resetForm2 = () => {
  // 重置新增数据表单
  Object.assign(addRollingForm, {
    userName: '',
    headPortrait: '',
    areaId: null,
    areaName: '',
    createTime: '',
    content: ''
  })
}
watch(
  () => props.isBatchImport,
  (val) => {
    visible.value = val
  }
)
onMounted(() => {
  handleGetGlobeState()
})

defineExpose({
  show,
  hide
})
</script>

<style lang="scss" scoped>
.scroll-style-box {
  :deep(.el-radio) {
    position: relative;
    border-radius: 6px 6px 6px 6px;
    border: 1px solid #e4e4e4;
    border-radius: 6px;
    width: 142px;
    height: 114px;
    .el-radio__input {
      position: absolute;
      right: 10px;
      top: 10px;
    }
    .scroll-style {
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
    }
  }
  :deep(.el-radio).is-checked {
    color: #3721ff !important;
    border: 1px solid #3721ff !important;
    background: #f7f6ff;
    .el-radio__inner {
      border-color: #3721ff !important;
      background: #3721ff !important;
    }
  }
}
</style>
<style scoped>
@import '@/styles/website.scss';
</style>
<style scoped lang="scss">
.users {
  :deep(.el-form-item__content) {
    display: block;
  }
}
:deep(.el-date-editor) {
  width: 100%;
}
</style>
